﻿namespace YunQue.DataBase.Extensions
{
    /// <summary>
    /// EFCore查询扩展方法
    /// </summary>
    public static class EFCoreExtension
    {
        /// <summary>
        /// WhereIf扩展方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="condition"></param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, bool condition, Expression<Func<T, bool>> predicate) where T : class
        {
            if (condition)
            {
                return source.Where(predicate);
            }
            return source;
        }
        /// <summary>
        /// 分页查询扩展方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static async Task<(int count, List<T> datas)> QueryDataByPageAsync<T>(this IQueryable<T> source, int pageIndex, int pageSize) where T : class
        {
            int count = await source.CountAsync();
            var datas = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToListAsync();
            return (count, datas);
        }
    }
}
